<template>
  <div style="width: 500px; margin: auto">
    <h1>登录页面</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName" />
      </el-form-item>
      <el-form-item label="密码" prop="userPwd">
        <el-input v-model="ruleForm.userPwd" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { login } from "../api/api";

import type { FormInstance, FormRules } from "element-plus";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  userName: "",
  userPwd: "",
});

const rules = ref({
  userName: [
    { required: true, message: "用户名不能为空", trigger: "blur" },
    { min: 8, message: "用户名不能小于8位", trigger: "blur" },
  ],
  userPwd: [
    { required: true, message: "密码不能小于6位", trigger: "blur" },
    {
      pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/,
      message: "密码必须8位！且包含大写字母和数字",
      trigger: "blur",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      login(ruleForm.value).then((res) => {
        if (res.data.flag) {
          ElMessage.success("登录成功");
          sessionStorage.setItem("token", res.data.data.token);
          sessionStorage.setItem("user", JSON.stringify(res.data.data.user));
          router.push("/home");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 页面加载钩子函数
onMounted(() => {});
</script>
